import os
import json
import re
import regex
from transformers import AutoTokenizer
from transformers import LlamaTokenizer

def read_rust_code(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
            rust_code = file.read()
        return rust_code
    except UnicodeDecodeError:
        return ""

def replace_prefix(file_path, prefix_original, prefix_new):
    if file_path.startswith(prefix_original):
        return file_path.replace(prefix_original, prefix_new, 1)
    else:
        return file_path  # 如果路径不匹配，则返回原始路径


def token_cal(text, tokenizer_path):
    tokenizer = LlamaTokenizer.from_pretrained(tokenizer_path)
    tokens = tokenizer.tokenize(text)
    token_cnt = len(tokens)
    return token_cnt



def extract_function_name(s):
    end_index = s.find('(')
    if end_index == -1:
        return ''  # 没有找到左括号，返回空字符串

    stack_angle_bracket = 0
    index = end_index - 1
    while index >= 0:
        if s[index] == '>':
            stack_angle_bracket += 1
            index -= 1
            while stack_angle_bracket and index >= 0:
                if s[index] == '>':
                    stack_angle_bracket += 1
                elif s[index] == '<':
                    stack_angle_bracket -= 1
                index -= 1
            # 去掉<前的::，确保index不越界
            while index >= 0 and s[index] == ':':
                index -= 1
            end_index = index + 1
            continue

        if s[index] == ':':
            start_index = index + 1
            break
        index -= 1
    else:
        start_index = 0  # 如果没有找到冒号，则从开始位置开始

    return s[start_index:end_index].strip()





def extract_outermost_parentheses_content(function_signature):
    # 正则表达式匹配最外层括号及其内容
    pattern = r'\((?:[^()]+|(?R))*\)'  # 使用递归匹配
    match = regex.search(pattern, function_signature)
    if match:
        return match.group(0)[1:-1].strip()

    return ""


def count_parameters(function_signature):
    params_str = extract_outermost_parentheses_content(function_signature)
    if not params_str:
        return 0

    # 使用栈来跟踪嵌套括号
    param_count = 0
    in_parameter = False
    parentheses_stack = []
    switch_double_quotation = 0
    switch_single_quotation = 0

    for char in params_str:
        if char == '(' or char == '<' or char == '{' or char == '[':
            parentheses_stack.append(char)
        elif char == ')' or char == '>' or char == '}' or char == ']':
            if parentheses_stack:
                parentheses_stack.pop()
        elif char == '"':
            switch_double_quotation = 1 - switch_double_quotation
        elif char == "'":
            switch_single_quotation = 1 - switch_single_quotation

        elif char == ',':
            if not parentheses_stack and switch_single_quotation == 0 and switch_double_quotation == 0:
                param_count += 1
        else:
            # 检查是否为参数的开始
            if not in_parameter:
                in_parameter = True
                param_count += 1

    # 检查是否有 'self', '&self', '&mut self' 在参数列表中
    for param in params_str.split(','):
        trimmed_param = param.strip()
        if trimmed_param in ['self', '&self', '&mut self']:
            param_count -= 1  # 如果有上下文引用，参数数量减一
    return param_count




'''
function: 根据"."分割字符串，且当.出现在括号或引号中时忽略它
output: 子字符串列表
'''
def split_function(str_functions):
    # 括号栈
    stack_bracket = []
    switch_double_quotation = 0
    switch_single_quotation = 0
    sub_start_index = 0
    list_str_function = []
    # input为空，则返回空列表
    if not str_functions:
        return list_str_function

    for index, char in enumerate(str_functions):
        if char in "({[<":
            stack_bracket.append(char)
        elif char in ")}]>":
            if stack_bracket:
                stack_bracket.pop()
        elif char == '"':
            switch_double_quotation = 1 - switch_double_quotation
        elif char == "'":
            switch_single_quotation = 1 - switch_single_quotation
        elif char == '.':
            if not stack_bracket and switch_single_quotation == 0 and switch_double_quotation == 0:
                # 分割
                if str_functions[sub_start_index: index].strip().endswith(")"):
                    list_str_function.append(str_functions[sub_start_index: index].strip())

                sub_start_index = index + 1
                if sub_start_index > len(str_functions):
                    break

    if sub_start_index < len(str_functions):
        if str_functions[sub_start_index:].strip().endswith(")"):
            list_str_function.append(str_functions[sub_start_index:].strip())

    # 去重
    list_str_function = list(set(list_str_function))
    return list_str_function



def read_json(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到。")
    except json.JSONDecodeError:
        print(f"文件 {file_path} 不是有效的JSON文件。")
    except Exception as e:
        print(f"读取文件 {file_path} 时发生错误: {e}")


def path_normalized(file_path):
    normalized_path = os.path.normpath(file_path)
    normalized_path = normalized_path.replace('\\', '/')
    return normalized_path

# 适用于list和dict
def save_data_to_json(data, file_path):
    # 创建目录
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)


def total_dict_lengths(json_file_path):
    total_length = 0

    # 读取 JSON 文件
    with open(json_file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)

        # 遍历每个字典
        for key, value in data.items():
            total_length += len(value)

    return total_length


def get_first_level_subdirectories(directory):
    subdirectories = []
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        if os.path.isdir(item_path):
            subdirectories.append(item_path)
    return subdirectories


# 提取路径的前n级，不适用于相对路径
def get_n_levels_subdirectory(path, n):
    # 将路径按分隔符分割
    parts = path.split(os.sep)
    limited_parts = parts[:n]
    return os.sep.join(limited_parts)


# 通过"/"提取路径的前n级
def get_n_levels_subdirectory_base_string(path, n):
    # 以'/'为分隔符分割路径
    parts = path.split("/")

    # 提取前 n 级，并确保结果为目录格式（带/）
    limited_parts = parts[:n]

    # 重新组合成路径
    return "/".join(limited_parts) + "/" if limited_parts else ""


def get_last_directory_name(path):
    return os.path.basename(os.path.normpath(path))


'''
input: 文件路径file_path, 要添加的内容new_content
output: 文件已被修改，返回原始文件的内容
'''
def modify_rs_file(file_path, new_content):
    # 1. 读取原始文件内容
    with open(file_path, 'r', encoding='utf-8') as file:
        original_content = file.read()

    # 2. 将新内容添加到文件末尾
    with open(file_path, 'a', encoding='utf-8') as file:
        file.write("\n" + new_content)

    # print(f"新内容已添加到 {file_path}")

    return original_content

'''
恢复文件
'''
def restore_rs_file(file_path, original_content):
    # 4. 恢复原始文件内容
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(original_content)

    # print(f"{file_path} 已恢复为原始状态")


def perform_operations(file_path):
    # 3. 在这里执行你需要的操作
    print(f"正在执行对 {file_path} 的操作...")

    # 示例：运行一些命令
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
        print(content)
    # os.system(f"cargo check")  # 示例操作，可以根据需要替换


def count_json_files(directory):
    # 确保输入的路径是一个目录
    if not os.path.isdir(directory):
        print(f"{directory} 不是一个有效的目录")
        return 0

    json_file_count = 0

    # 遍历目录中的文件
    for filename in os.listdir(directory):
        if filename.lower().endswith('.json'):  # 检查文件是否以.json结尾
            json_file_count += 1

    return json_file_count